package org.ziegler.jvm.cp7.hotLoad;

import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.InvocationTargetException;

public class ClassLoaderTest {

    public ClassLoaderTest() {
        System.out.println("222");
    }

    public static void main(String[] args) throws ClassNotFoundException, IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException, InterruptedException {

        final ClassLoaderTest classLoaderTest = new ClassLoaderTest();
        classLoaderTest.printTest();

        while (true) {

            // 重新加载
            final MyClassLoader myClassLoader = new MyClassLoader();

            final Object o = myClassLoader.loadClass("org.ziegler.jvm.cp7.hotLoad.ClassLoaderTest")
                    .getDeclaredConstructor().newInstance();


            classLoaderTest.printTest();


            Thread.sleep(10000);
        }

    }

    void printTest() {
        System.out.println("bbb");
    }

    private static class MyClassLoader extends ClassLoader {
        @Override
        public Class<?> loadClass(String name) throws ClassNotFoundException {

            try {
                final String fileName = name.substring(name.lastIndexOf(".") + 1) + "aaa.class";
                final InputStream is = getClass().getResourceAsStream(fileName);
                if (is == null) {
                    return super.loadClass(name);
                }

                final byte[] b = new byte[is.available()];
                is.read(b);

                return defineClass(name, b, 0, b.length);
            } catch (IOException e) {
                throw new ClassNotFoundException(name);
            }
        }
    }
}
